package com.java.socket.tcp.singleclient.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 单线程socket服务端
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class ServerSockectExample {

    public static void main(String[] args) {
        try {
            // 创建ServerSocket对象, 监听指定的端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务端Socket启动...");
            // 侦听连接此服务端的客户端连接并接受它，该方法会阻塞连接
            Socket socket = serverSocket.accept();
            // 从Socket中获取一个输入流，用于获取客户端的输入信息
            InputStream inputStream = socket.getInputStream();
            // 将字节流转换成字符流，提高读取效率
            InputStreamReader reader = new InputStreamReader(inputStream);
            // 将字符流转换成缓冲字符流，提高效率
            BufferedReader bufferedReader = new BufferedReader(reader);
            // 获取客户端的输入信息
            String temp = null;
            StringBuffer info = new StringBuffer();
            while ((temp = bufferedReader.readLine()) != null) {
                info.append(temp);
            }
            System.out.println("从客户端接受的消息: " + info.toString());


            // 从Socket中获取一个输出流，用于向当前连接的客户端发送反馈信息
            OutputStream outputStream = socket.getOutputStream();
            // 将字节流转换成字符流，提高写效率
            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            String message = "来自服务端的消息...";
            PrintWriter printWriter = new PrintWriter(writer);
            printWriter.write(message);
            printWriter.flush();

            // 关闭资源
            printWriter.close();
            writer.close();
            outputStream.close();
            bufferedReader.close();
            reader.close();
            inputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
